package com.star95.springbooti18n.exception;

import com.star95.springbooti18n.common.constants.MessagesEnum;
import com.star95.springbooti18n.common.util.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;

/**
 * 异常工具类
 *
 */
@Slf4j
public class ExceptionUtil {
    public static BusinessException exception(MessagesEnum errorCode) {
        String msg = MessageUtils.getMessage(errorCode.getCode(), null);
        if (StringUtils.isEmpty(msg)) {
            msg = errorCode.getMsg();
        }
        return exception0(errorCode.getCode(), msg);
    }

    public static BusinessException exception(MessagesEnum errorCode, Object... params) {
        String msg = MessageUtils.getMessage(errorCode.getCode(), params);
        if (StringUtils.isEmpty(msg)) {
            MessageFormat format = new MessageFormat(errorCode.getMsg(), LocaleContextHolder.getLocale());
            msg = format.format(params);
        }
        return exception0(errorCode.getCode(), msg);
    }

    public static BusinessException exception0(String code, String message) {
        return new BusinessException(code, message);
    }
}
